package com.dycx.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Abel
 * @date: 2021-06-19
 * 读取jar包中资源文件路径工具类
 */
@Slf4j
public class ResourceFileUtil {
    private static final String sourceTemplatePath;

    static {
        //静态方法调用一次　
        sourceTemplatePath = StringUtils.join(getPath(), File.separator, "resources");
    }

    private static String getPath() {
        ApplicationHome home = new ApplicationHome(ResourceFileUtil.class);
        File jarFile = home.getSource();
        String parent = jarFile.getParent();
        return parent;
    }

    public static String getDownloadsPath() {
        String downloadsTemplatePath = StringUtils.join(getPath(), File.separator, "resources", File.separator, "downloads");
        File file = new File(downloadsTemplatePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
        return downloadsTemplatePath;
    }

    //可解决本地能读取文件，打包后读取不到问题
    public static String getJarResourceFile(String path) {

        //获取容器资源解析器
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //获取所有匹配的文件
            Resource[] resources = resolver.getResources(path);
            List<File> list = new ArrayList<>(resources.length);
            Arrays.stream(resources).forEach(resource -> {
                try {
                    InputStream stream = resource.getInputStream();
                    String targetFilePath = StringUtils.join(sourceTemplatePath, File.separator, path);
                    File ttfFile = new File(targetFilePath);
                    FileUtils.copyInputStreamToFile(stream, ttfFile);
                    list.add(ttfFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            if (list != null && list.size() > 0) {
                return list.get(0).getPath();
            }
            throw new RuntimeException("文件名称或文件路径有误，请检查文件是否存在！"+path);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 读取JSON文件转换为字符串
     *
     * @param filePath
     * @return
     */
    public static String readJsonFile(String filePath) {
        String jsonStr = "";
        try {
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            InputStream inputStream = classPathResource.getInputStream();
            Reader reader = new InputStreamReader(inputStream, "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

//        String newPath = ResourceFileUtil.getJarResourceFile(filePath);
//
//        String jsonStr = "";
//        try {
//            File jsonFile = new File(newPath);
//            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
//            int ch = 0;
//            StringBuffer sb = new StringBuffer();
//            while ((ch = reader.read()) != -1) {
//                sb.append((char) ch);
//            }
//            reader.close();
//            jsonStr = sb.toString();
//            return jsonStr;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            return null;
//        }
    }

}
